<template>
  <div id="box">
    <!-- 图表展示位置 -->
    <basic-card class="card1">
      <!-- 日期选择 -->
      <!-- <van-cell is-link @click="showPopup">展示弹出层</van-cell> -->
      <div style="font-size: 15px; margin-top: 10px; color: black;padding-left:10px;padding-right: 20px ;display: flex;
  justify-content: space-between;">
        <span style="font-size: 15px; "> 收款方式占比</span>
        <span
            @click="showPopup"

        >
          <!-- {{currentDate.getFullYear()}}年{{currentDate.getMonth()+1}}月 -->
          {{ selectYear }}年{{ selectMonth }}月
          <van-icon name="arrow-down"/>
        </span>
      </div>
      <van-popup v-model="show" position="top"
      >
        <div>
          <van-datetime-picker
              v-model="currentDate"
              type="year-month"
              title="选择年月"
              :min-date="minDate"
              :max-date="maxDate"
              :formatter="formatter"
              @confirm="confirmClick"
              @cancel="cancelClick"
          />
        </div
        >
      </van-popup>

      <!-- 图表展示 -->
      <div
          id="myChart"
          style="width: 320px; height: 270px"
          ref="my_chart"
      ></div>
    </basic-card>

    <!-- 下面的数据 -->
    <basic-card class="card2">
      <van-list
          v-model="loading"
          :finished="finished"
          finished-text=""
          @load="onLoad"
          class="myList"
          @list-text-line-height="100"
      >
        <van-cell
            class="myListItem"
            style="padding-top: 5px; padding-bottom: 1px"
        >
          <div>
            <span class="fontColor" style="font-size: 10px"
            >类别&nbsp; / &nbsp;比例</span
            >
            <span class="fontColor" style="font-size: 10px; float: right"
            >笔数</span
            >
          </div>
        </van-cell>
        <van-cell class="myListItem" v-for="(item, index) in chartData" :key="index">
          <div style="padding: 4px 0px">
<!--            <van-icon :color="color[index]" name="play"/>-->
            <span>{{ item.name }} </span>
            <span class="fontColor" style="font-size: 12px"
            >&nbsp; /&nbsp;{{ decimalToPercentage(item.value / sum) }}
            </span>
            <span style="float: right">{{ item.value.toLocaleString() }}</span>
          </div>
        </van-cell>
      </van-list>
    </basic-card>
  </div>
</template>

<script>
import BasicCard from "../BasicCard.vue";

export default {
  components: {BasicCard},
  name: "LineChart",
  data() {
    return {
      // 日期选择相关
      minDate: new Date(2018, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(),
      show: false,
      selectYear: 2023,
      selectMonth: 7,
      // 图表相关
      chartInstance: null,
      chartData: [],
      // color: null,

      // 列表相关
      sum: 0,
      // list: [],
      loading: false,
      finished: false,
      color1: [
        "rgb(105,219,219)",
        "rgb(162,230,148)",
        "rgb(110,220,174)",
        "rgb(255,137,138)",
        "rgb(255,217,123)",
        "rgb(245,167,190)",
        "#B1B2FF",
        "#fed9b7",
        "#e4c1f9",
        "#f7a072",
        "#b8e0d2",
        "#ff5d8f",
        "#49b6ff",
        "#ffc8dd",
      ],
      color2: [
        '#736f72',
        '#9a8f97',
        '#b2b2b2',
        '#c3baba',
        '#e9e3e6'
      ],

    };
  },
  methods: {
    showPopup() {
      this.show = true;
    },
    confirmClick(value) {

      this.selectYear = value.getFullYear();
      this.selectMonth = value.getMonth() + 1;
      this.show = false;
      this.getData();
    },
    cancelClick() {
      this.show = false;
    },
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      }
      return val;
    },
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1);
      //   }
      //   this.list = this.
      //   // 加载状态结束
      //   this.loading = false;

      //   // 数据全部加载完成
      //   if (this.list.length >= 40) {
      //     this.finished = true;
      //   }
      // }, 1000);

      // this.list = this.chartData;
      // 加载状态结束
      this.loading = false;
    },

    decimalToPercentage(decimal) {
      // 将小数转换为百分数并保留两位小数
      const percentage = (decimal * 100).toFixed(2);

      // 添加百分号
      return percentage + "%";
    },
    initChart() {
      this.chartInstance = this.$echarts.init(this.$refs.my_chart, null, {
        renderer: "svg",
      });
      //   this.chartInstance = this.$echarts.init(this.$refs.my_chart);
    },
    async getData() {
      // var startMonth = this.selectYear + "-" + (this.selectMonth);
      // const url = "http://192.168.32.178:8081/detailsmonth?id=1&startMonth=" + startMonth;
      // const url = "http://127.0.0.1:8082/merchanthome/detailsmonth?id=1&month="+this.selectMonth+"&year=" + this.selectYear;
      const url = "/merchanthome/detailsmonth?id=1&month="+this.selectMonth+"&year=" + this.selectYear;
      console.log(url);
      const { code, data } = await this.$http.get(
        // "http://192.168.32.178:8081/monthsum?startMonth=2022-07&endMonth=2023-08"
        url
      );

      // const jsonData = JSON.parse(data.data);
      // // jsonData格式："['icbc:3603', 'alipay:14109', 'others:6966', 'wechat:6804']"
      // const keys = jsonData.map(data=>data.split(':')[0])
      // const values = jsonData.map(data=>parseInt(data.split(':')[1]))

      const jsonData = data.data
      const keys = Object.keys(jsonData);
      const values = Object.values(jsonData);
      const dict = {
        alipay: "支付宝",
        wechat: "微信",
        icbc: "e支付",
        ccb: "建设",
        others: "其他",
      };
      // 将keys,values,dict合并成一个对象数组
      this.chartData = keys.map((key, index) => {
        return {
          name: dict[key],
          value: values[index],
        };
      });
      // console.log(this.chartData)

      // todo: 这个并没有真正发送网络请求
      // this.chartData = data
      // this.chartData = [
      //   {value: 777, name: "微信"},
      //   {value: 1048, name: "支付宝"},
      //   {value: 580, name: "工商"},
      //   {value: 484, name: "建设"},
      //   {value: 300, name: "其他"},
      // ];
      // 对chartData按照value进行排序
      this.chartData.sort((a, b) => {
        return b.value - a.value;
      });
      this.sum = this.chartData.reduce((sum, item) => {
        return sum + item.value;

      }, 0);
    },

    updateChart() {
      // 样式化中间的文字
      // const
      this.chartInstance.setOption(this.option);
    },
    ininDate() {
      this.selectYear = this.currentDate.getFullYear();
      this.selectMonth = this.currentDate.getMonth() + 1;
    },
  },
  watch: {
    chartData() {
      this.updateChart();
    },
    color() {
      this.updateChart();
    },
  },
  computed: {
    color(){
      // return this.$store.state.checked ? this.color2 : this.color1
      return this.$store.state.payPieColor[this.$store.state.styleNum]
    },
    option() {
      return {
        title: {
          text: "",
          left: "43%",
          top: "center",
        },


        tooltip: {
          trigger: "item",
        },
        // legend: {
        //   top: '5%',
        //   left: 'center'
        // },
        // grid: {
        //   x: 40,
        //   y: 0,
        //   x2: 0,
        //   y2: 10,
        // },
        series: [
          {
            name: "支付方式",
            type: "pie",
            center: ["50%", "50%"], // 默认全局居中
            radius: ["43%", "65%"],
            avoidLabelOverlap: false,


            label: {
              show: true,
              // position: 'center'
            },
            // 将图表的每一项都有个分隔
            //       itemStyle: {
            //   borderRadius: 3,
            //   borderColor: '#fff',
            //   borderWidth: 1
            // },
            emphasis: {
              label: {
                show: true,
                //   fontSize: 40,
                //   fontWeight: 'bold'
              },
            },
            labelLine: {
              show: true,
            },
            data: this.chartData,
            // // 将饼状图的旋转动画持续时间设为2000ms（2秒）
            animationDuration: 700,
            animationDurationUpdate: 700,
            // 将饼状图的动画渐变设置为线性
            animationEasing: 'linear',

          },
          {

            type: "scatter",
            data: [[0, 0]],
            symbolSize: 1,
            label: {
              position: "inside",
              distance: 0,
              show: true,
              formatter: ["{term|总笔数}", this.sum.toLocaleString()].join("\n"),
              color: "#000",
              fontSize: 17,
              lineHeight: 20,
              align: "center",
              rich: {
                term: {
                  fontSize: 11,
                  color: "rgb(197, 198, 199)",
                },
              },
            },
          },
        ],
        xAxis: {
          axisLabel: {show: false},
          axisLine: {show: false},
          splitLine: {show: false},
          axisTick: {show: false},
          min: -1,
          max: 1,
        },
        yAxis: {
          axisLabel: {show: false},
          axisLine: {show: false},
          splitLine: {show: false},
          axisTick: {show: false},
          min: -1,
          max: 1,
        },
        // color: [
        //   '#d4a373',
        //   '#faedcd',
        //   '#fefae0',
        //   '#e9edc9',
        //   '#ccd5ae'
        // ],
        // color: [
        //   '#cdb4db',
        //   '#ffc8dd',
        //   '#ffafcc',
        //   '#bde0fe',
        //   '#a2d2ff'
        // ],
        // color: [
        //   '#a3c4f3',
        //   '#90dbf4',
        //   '#8eecf5',
        //   '#98f5e1',
        //   '#b9fbc0'
        // ],
        color: this.color,
      };
    },
  },

  mounted() {
    this.ininDate();
    this.initChart();
    this.getData();

    this.updateChart();
    // console.log(this.chartInstance.getModel().option.color);
    // this.color = this.chartInstance.getModel().option.color;

    // console.log(this.sum);
    // console.log("....",this);
  },
};
</script>


<style scoped>
#box {
  background-color: rgb(247, 248, 250);
  padding-top: 10px;
  min-height: 667px;
}

/*
.card1 {
  width: 320px;
  margin: 5px auto;
  box-shadow: 2px 3px 4px rgba(0, 0, 0, 0.09);
  padding: 5px 10px;
  text-align: center;
}
 */

.card1 {
  width: 325rem;
  margin: 5rem auto;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.15);;
  padding: 5rem 10rem;
  text-align: center;
}


.card2 {
  width: 325rem;
  margin: 5rem auto;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.15);;
  margin-top: 10rem;
  margin-bottom: 10rem;
  padding: 5rem 10rem;
  animation-name: animationCard2;
  animation-duration: 0.6s;
}


/*
.card2 {
  width: 330px;
  margin: 5px auto;
  box-shadow: 2px 3px 4px rgba(0, 0, 0, 0.09);
  margin-top: 10px;
  margin-bottom: 10px;
  padding: 5px 10px;
  animation-name: animationCard2;
  animation-duration: 0.6s;
}
 */



@keyframes animationCard2 {
  0% {
    transform: translateY(200px);
  }
  100% {
    transform: translateY(0);
  }
}

.myList {
  text-align: left;
  /* padding: 5px; */
}

.myListItem {
  /* border-bottom: 1px solid #ebedf0; */
  /* height: 60px; */
  /* margin: auto,0; */
}

.fontColor {
  color: rgb(197, 198, 199);
}
</style>